<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\model\ClientAccountModel;
use app\model\ClientProjectMediaMonthlyStatModel;
use app\model\ClientProjectMonthlyStatModel;
use app\model\CrontabTaskModel;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

// 已测试
class ClientProjectMonthlyStatWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    // 已测试
    protected function configure()
    {
        // 指令配置
        $this->setName('client_project_monthly_stat_work');
        $this->setDescription('客户项目&媒体，月消耗汇总');
        $this->addArgument('start_month', Argument::OPTIONAL, '月份');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======客户项目月消耗汇总开始' . date('Y-m-d H:i:s', time()) . '=======');
        $statMonth = $input->getArgument('start_month') ?: date('Ym', strtotime('-1 day'));
        $statMonth = intval($statMonth);
        if ($statMonth == date('Ym')) {
            // 当月
            if (date('d') == 1) {
                $startDate = date('Ym01', strtotime('-1 day'));
                $endDate = date('Ymd', strtotime("{$startDate}"));
            } else {
                $startDate = date('Ym01');
                $endDate = date('Ymd', strtotime('-1 day'));
            }
        } else {
            $startDate = $statMonth . '01';
            $endDate = date('Ymd', strtotime("{$startDate} +1 month -1 day"));
        }

        // oe
        $oeData = ClientAccountModel::alias('a')
            ->join(['habo_oe_advertiser_daily_stat' => 'b'], 'a.advertiser_id=b.advertiser_id')
            ->whereBetween('b.stat_date', [$startDate, $endDate])
            ->where('a.media_id', CommonEnum::OE_MEDIA)
            ->field('a.company_id,a.media_id,b.project_id,a.client_id,sum(b.cost) as cost,sum(b.cash_cost) as cash_cost')
            ->group('a.client_id,b.project_id')
            ->select()->toArray();
        // ks
        $ksData = ClientAccountModel::alias('a')
            ->join(['habo_ks_advertiser_daily_stat' => 'b'], 'a.advertiser_id=b.advertiser_id')
            ->whereBetween('b.stat_date', [$startDate, $endDate])
            ->where('a.media_id', CommonEnum::KS_MEDIA)
            ->field('a.company_id,a.media_id,b.project_id,a.client_id,sum(b.daily_charge) as cost,sum(b.real_charged) as cash_cost')
            ->group('a.client_id,b.project_id')
            ->select()->toArray();
        // qq
        $qqData = ClientAccountModel::alias('a')
            ->join(['habo_qq_advertiser_daily_stat' => 'b'], 'a.advertiser_id=b.advertiser_id')
            ->whereBetween('b.stat_date', [$startDate, $endDate])
            ->where('a.media_id', CommonEnum::QQ_MEDIA)
            ->field('a.company_id,a.media_id,b.project_id,a.client_id,sum(b.cost) as cost,sum(b.cash_cost) as cash_cost')
            ->group('a.client_id,b.project_id')
            ->select()->toArray();
        $allData = array_merge($oeData, $ksData, $qqData);
        try {
            if (! empty($allData)) {
                $sumData = [];
                foreach ($allData as $val) {
                    if ($val['project_id'] == 0) {
                        continue;
                    }
                    // 汇总客户媒体数据
                    if ($val['cost'] > 0 || $val['cash_cost'] > 0) {
                        if (isset($sumData[$val['client_id'] . '-' . $val['project_id']])) {
                            $sumData[$val['client_id'] . '-' . $val['project_id']]['cost'] += $val['cost'];
                            $sumData[$val['client_id'] . '-' . $val['project_id']]['cash_cost'] += $val['cash_cost'];
                        } else {
                            $sumData[$val['client_id'] . '-' . $val['project_id']] = [
                                'cost' => $val['cost'],
                                'cash_cost' => $val['cash_cost'],
                                'company_id' => $val['company_id'],
                                'client_id' => $val['client_id'],
                                'project_id' => $val['project_id'],
                            ];
                        }
                        $createData = [
                            'company_id' => $val['company_id'],
                            'client_id' => $val['client_id'],
                            'project_id' => $val['project_id'],
                            'media_id' => $val['media_id'],
                            'stat_month' => $statMonth,
                            'cost' => $val['cost'],
                            'cash_cost' => $val['cash_cost'],
                        ];
                        // 判断是否存在
                        $isHas = ClientProjectMediaMonthlyStatModel::where('client_id', $val['client_id'])
                            ->where('project_id', $val['project_id'])
                            ->where('media_id', $val['media_id'])
                            ->where('stat_month', $statMonth)
                            ->find();
                        if ($isHas) {
                            ClientProjectMediaMonthlyStatModel::where('id', $isHas['id'])->update($createData);
                        } else {
                            ClientProjectMediaMonthlyStatModel::create($createData);
                        }
                    }
                }
                // 汇总客户数据
                foreach ($sumData as $val) {
                    $createData = [
                        'company_id' => $val['company_id'],
                        'client_id' => $val['client_id'],
                        'project_id' => $val['project_id'],
                        'stat_month' => $statMonth,
                        'cost' => $val['cost'],
                        'cash_cost' => $val['cash_cost'],
                    ];
                    // 判断是否存在
                    $isHas = ClientProjectMonthlyStatModel::where('client_id', $val['client_id'])
                        ->where('project_id', $val['project_id'])
                        ->where('stat_month', $statMonth)
                        ->find();
                    if ($isHas) {
                        ClientProjectMonthlyStatModel::where('id', $isHas['id'])->update($createData);
                    } else {
                        ClientProjectMonthlyStatModel::create($createData);
                    }
                }
            }
        } catch (\Exception $e) {
            dump($e);
            exit;
        }

        $output->writeln('=======客户项目月消耗汇总结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }
}
